#####################################################
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# FileName: my_monitor.py
# Description: 每五秒向influx数据库写入cpu,memory,disk,network占用率
# Version: 1.0
# Author: 管一鸣
# Date: 2022-05-15
# Platform: ubuntu
#####################################################
import _thread
import time
import socket
import psutil
from influxdb import InfluxDBClient

#  连接数据库
client = InfluxDBClient('localhost', 8086, 'root', '123456')
# get database
database_list = client.get_list_database()
for elem in database_list:
    if elem['name'] == 'my_monitor':
        client.drop_database('my_monitor')
        break

time.sleep(2)
client.create_database('my_monitor')
client.switch_database('my_monitor')

client.query('CREATE CONTINUOUS QUERY "cq_1m" ON "my_monitor" BEGIN '
             'SELECT mean("cpu_percent") AS "mean_cpu", '
             'mean("mem_percent") AS "mean_mem", '
             'mean("disk_percent") AS "mean_disk", '
             'mean("network_percent") AS "mean_network_percent" '
             'INTO "average_info" '
             'FROM "all_info" '
             'GROUP BY time(1m) '
             'END')


# 获取本机IP
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 0))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP


ip = get_ip()

cpu_info = ""
memory_info = ""
disk_info = ""
network_info = ""


def get_all(sec):
    while True:
        global cpu_info, memory_info, disk_info, network_info
        cpu_info = psutil.cpu_percent(0)
        memory_info = psutil.virtual_memory()
        disk_info = psutil.disk_usage('/')
        network_if_addr = psutil.net_if_addrs()
        network_need = ""
        for item in network_if_addr:
            if network_if_addr.get(item)[0].address == ip:
                network_need = item
        network_info = psutil.net_io_counters(pernic=True)[network_need]
        network_percent = float(network_info.bytes_sent) / float(network_info.bytes_recv) * 100
        network_percent = round(network_percent,2)
        text = [
            {
                "measurement": "all_info",
                "tags": {
                    "host": ip
                },
                "fields": {
                    "cpu_percent": cpu_info,
                    "mem_percent": memory_info.percent,
                    "disk_percent": disk_info.percent,
                    "network_percent": network_percent,
                }
            }
        ]
        # print(text)
        client.write_points(text)
        time.sleep(sec)


if __name__ == '__main__':
    get_all(5)
